﻿using System;
using System.Web.UI;
using System.Web.Configuration;
using System.Data;
using System.Security.Cryptography;
using System.Text;
public partial class admin_basicData_adminManager : Page
{
    public string Html_Dept = "";
    public string Html_Dept_Detail = "";
    DBHelper db = new DBHelper(WebConfigurationManager.ConnectionStrings["connString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetDept();
            loadData();
        }
    }

    private void GetDept()
    {
        int i = 0;
        Html_Dept = "";
        DataTable dt = db.getList("select * from dict_dept where [isUsing]=1 order by id");
        foreach (DataRow dr in dt.Rows)
        {
            if (i == 0)
            {
                Html_Dept += "<li role=\"presentation\" class=\"active\"><a href=\"#dept_" + dr["id"].ToString() + "\" role=\"tab\" data-toggle=\"tab\">" + dr["mc"].ToString() + "</a></li>";
            }
            else
            {
                Html_Dept += "<li role=\"presentation\"><a href=\"#dept_" + dr["id"].ToString() + "\" role=\"tab\" data-toggle=\"tab\">" + dr["mc"].ToString() + "</a></li>";
            }
            i = 1;
        }
    }

    private void loadData()
    {
        dept_id.Value = "";
        int i = 0;
        DataTable dt = db.getList("select * from dict_dept where [isUsing]=1 order by id");
        foreach (DataRow dr in dt.Rows)
        {
            dept_id.Value = dept_id.Value + "|" + dr["id"].ToString();
            if (i == 0)
            { Html_Dept_Detail += "<div role=\"tabpanel\" class=\"tab-pane active\" id=\"dept_" + dr["id"].ToString() + "\">"; }
            else
            { Html_Dept_Detail += "<div role=\"tabpanel\" class=\"tab-pane\" id=\"dept_" + dr["id"].ToString() + "\">"; }

            Html_Dept_Detail += "<div class=\"box-body\">";
            Html_Dept_Detail += "<table id=\"table_" + dr["id"].ToString() + "\" class=\"table table-bordered table-striped\">";
            Html_Dept_Detail += "<thead>";
            Html_Dept_Detail += "<tr>";
            Html_Dept_Detail += "<th></th>";
            Html_Dept_Detail += "<th>工号</th>";
            Html_Dept_Detail += "<th>姓名</th>";
            Html_Dept_Detail += "<th>账号</th>";
            Html_Dept_Detail += "<th>角色</th>";
            Html_Dept_Detail += "<th>可用</th>";
            Html_Dept_Detail += "<th>操作</th>";
            Html_Dept_Detail += "</tr>";
            Html_Dept_Detail += "</thead>";
            Html_Dept_Detail += "<tbody>";
            DataTable dt1 = db.getList("v_user", "ID,userName,userAccount,userpwd,isusing,roleID,roleName,userbh", "dept=" + dr["id"].ToString(), "userName");
            foreach (DataRow dr1 in dt1.Rows)
            {
                Html_Dept_Detail += "<asp:Repeater ID=\"rpt_hz\" runat=\"server\">";
                Html_Dept_Detail += "<ItemTemplate>";
                Html_Dept_Detail += "<tr>";
                Html_Dept_Detail += "<td>" + dr1["id"].ToString() + "</td>";
                Html_Dept_Detail += "<td>" + dr1["userbh"].ToString() + "</td>";
                Html_Dept_Detail += "<td>" + dr1["userName"].ToString() + "</td>";
                Html_Dept_Detail += "<td>" + dr1["userAccount"].ToString() + "</td>";
                Html_Dept_Detail += "<td>" + dr1["roleName"].ToString() + "</td>";
                Html_Dept_Detail += "<td>" + SQ_Eval_Pub.GetIsUsing(dr1["isUsing"].ToString()) + "</td>";
                Html_Dept_Detail += "<td><a data-toggle=\"modal\" data-target=\"#userManager\" data-action=\"update\" data-bid=\"" + dr1["id"].ToString() + "\">修改</a></td>";
                Html_Dept_Detail += "</tr>";
            }
            Html_Dept_Detail += "</tbody>";
            Html_Dept_Detail += "</table>";
            Html_Dept_Detail += "</div>";
            Html_Dept_Detail += "</div>";
            i = 1;
        }

        DataTable dtRole = db.getList("[Role]", "ID,roleName", "isUsing=1 AND roleName<>'1'", "ID DESC");
        ddlRole.DataSource = dtRole;
        ddlRole.DataTextField = "roleName";
        ddlRole.DataValueField = "ID";
        ddlRole.DataBind();

        DataTable dtDept = db.getList("[dict_dept]", "ID,mc", "isUsing=1", "mc");
        ddlDept.DataSource = dtDept;
        ddlDept.DataTextField = "mc";
        ddlDept.DataValueField = "ID";
        ddlDept.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string errmsg = "";

        bool res = checkAccountAndName(StringHelper.SafeSqlInput(txtAccount.Text.Trim()), StringHelper.SafeSqlInput(txtName.Text.Trim()), "0", ref errmsg);
        if (res)
        {
            string insertSql = "INSERT INTO [user] (userName,userAccount,userpwd,isusing,roleID,userbh,dept) VALUES (N'" + StringHelper.SafeSqlInput(txtName.Text.Trim()) + "','" + StringHelper.SafeSqlInput(txtAccount.Text.Trim()) + "','" + Md5Encrypt(StringHelper.SafeSqlInput(txtPwd.Text.Trim())) + "'," + StringHelper.SafeSqlInput(ddlIsUsing.SelectedValue) + "," + StringHelper.SafeSqlInput(ddlRole.SelectedValue) + ",'" + txtUserbh.Text + "','" + StringHelper.SafeSqlInput(ddlDept.SelectedValue) + "')";

            int i = db.executeNoneQuery(insertSql, ref errmsg);
            if (i > 0)
            {
                Response.Write(CommonHelper.alertMsgAndRedirect("添加成功", Request.Url.LocalPath + Request.Url.Query));
            }
            else
            {
                Response.Write(CommonHelper.alertMsg("添加失败," + errmsg));
            }
        }
        else
        {
            Response.Write(CommonHelper.alertMsgAndRedirect("添加失败\r\n" + errmsg, Request.Url.LocalPath + Request.Url.Query));
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (hidBID.Value.Trim() != "")
        {
            string errmsg = "";
            string updateSql = "";
            if (selEditPwd.Checked)
            {
                updateSql = "UPDATE [user] SET userName=N'" + txtName.Text + "',userpwd='" + Md5Encrypt(StringHelper.SafeSqlInput(txtPwd.Text.Trim())) + "',isusing=" + StringHelper.SafeSqlInput(ddlIsUsing.SelectedValue) + ",roleID=" + StringHelper.SafeSqlInput(ddlRole.SelectedValue) + ",dept='" + ddlDept.SelectedValue + "' WHERE ID=" + StringHelper.SafeSqlInput(hidBID.Value);
            }
            else
            {
                updateSql = "UPDATE [user] SET userName=N'" + txtName.Text + "', isusing=" + StringHelper.SafeSqlInput(ddlIsUsing.SelectedValue) + ",roleID=" + StringHelper.SafeSqlInput(ddlRole.SelectedValue) + ",dept='" + ddlDept.SelectedValue + "' WHERE ID=" + StringHelper.SafeSqlInput(hidBID.Value);
            }

            int i = db.executeNoneQuery(updateSql, ref errmsg);
            if (i > 0)
            {
                Response.Write(CommonHelper.alertMsgAndRedirect("修改成功", Request.Url.LocalPath + Request.Url.Query));
            }
            else
            {
                Response.Write(CommonHelper.alertMsg("修改失败," + errmsg));
            }
        }
        else
        {
            Response.Write(CommonHelper.alertMsgAndRedirect("添加失败\r\n", Request.Url.LocalPath + Request.Url.Query));
        }

    }

    protected void btnGet_Click(object sender, EventArgs e)
    {
        if (hidBID.Value.Trim() != "")
        {
            DataTable dt = db.getList("1", "[user]", "ID,userName,userAccount,userpwd,isusing,roleID,userbh,dept", "ID=" + StringHelper.SafeSqlInput(hidBID.Value), "isUsing,userbh asc");
            if (dt.Rows.Count > 0)
            {
                txtName.Text = dt.Rows[0]["userName"].ToString().Trim();
                txtAccount.Text = dt.Rows[0]["userAccount"].ToString().Trim();
                txtPwd.Text = dt.Rows[0]["userpwd"].ToString().Trim();
                txtUserbh.Text = dt.Rows[0]["userbh"].ToString().Trim();
                try
                {
                    ddlRole.SelectedValue = dt.Rows[0]["roleID"].ToString().Trim();
                }
                catch
                {
                    ddlRole.SelectedIndex = 0;
                }
                try
                {
                    ddlDept.SelectedValue = dt.Rows[0]["dept"].ToString().Trim();
                }
                catch
                {
                    ddlDept.SelectedIndex = 0;
                }
                ddlIsUsing.SelectedValue = dt.Rows[0]["isUsing"].ToString().Trim() == "True" ? "1" : "0";
            }
        }
    }
    private bool checkAccountAndName(string account, string name, string userid, ref string error)
    {
        bool res = true;

        if (db.getCount("[user]", "userAccount='" + account + "' AND ID<>" + userid) > 0)
        {
            res = false;
            error += "账号已存在,请重新填写";
        }

        if (db.getCount("[user]", "userName='" + name + "' AND ID<>" + userid) > 0)
        {
            res = false;
            error += "姓名已存在,请重新填写";
        }

        return res;
    }
    public string Md5Encrypt(string data)
    {
        MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
        byte[] dataHashed = md5Hasher.ComputeHash(Encoding.Default.GetBytes(data));
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < dataHashed.Length; i++)
        {
            sBuilder.Append(dataHashed[i].ToString("x2"));
        }
        return sBuilder.ToString();
    }
}